package edu.put.sk.nrpp.ospf.packet;

import java.net.InetAddress;
import java.net.UnknownHostException;

import edu.put.sk.nrpp.*;

/**
 * 
 * @author kevin
 * TODO: rewrite this (using only _data field) without calculating data in constructor.
 */

abstract public class OSPFPacket {
	protected Bit[] data;
	
	public static OSPFPacket getInstance(IPPacket ipPacket) throws Exception{
		return getInstance(ipPacket.getData());
	}
	
	public static OSPFPacket getInstance(Bit[] data) throws Exception{
		int version=Bit.toInt(Bit.cut(data, 0, 7));
		int type=Bit.toInt(Bit.cut(data, 8, 15));
//		System.out.println("OSPF type: "+type);
		if(version==2){
			if(type==1){
				return new OSPFPacketVersion2Type1(data);
			}else if(type==2){
				return new OSPFPacketVersion2Type2(data);
			}else if(type==3){
				return new OSPFPacketVersion2Type3(data);
			}else if(type==4){
				return new OSPFPacketVersion2Type4(data);
			}else if(type==5){
				//return new OSPFPacketVersion2Type5(data);
			}
		}

		
		return null;
	}
	
	public int getAreaID(){
		return Bit.toInt(Bit.cut(data, 64, 95));
	}
	
	public InetAddress getRouterID() throws UnknownHostException{
		return Bit.toInetAddres(Bit.cut(data, 32, 63));
	}
	
	public int getVersion(){
		return Bit.toInt(Bit.cut(data, 0, 7));
	}
	
	public int getPacketLength(){
		return Bit.toInt(Bit.cut(data, 16, 31));
	}
	
	public int getCheckSum(){
		return Bit.toOnesComplement(Bit.cut(data, 96, 111));
	}
	
	public int getInstanceId(){
		return Bit.toInt(Bit.cut(data, 112, 119));
	}
	
	
	
	protected OSPFPacket(Bit[] data){
		this.data=data;
	}
	
	protected OSPFPacket(IPPacket ipPacket){
		this(ipPacket.getData());
	}
	
}
